package com.anlogic.sdk.toolchain;

import org.eclipse.cdt.managedbuilder.core.BuildException;
import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.embedcdt.managedbuild.cross.riscv.core.ToolchainConfiguration;
import org.eclipse.embedcdt.managedbuild.cross.riscv.core.ToolchainDefinition;

import com.anlogic.sdk.utils.toolchain.ToolchainUtils;

public class RiscvToolchain {
	public static void setToolchainName(IProject project, String toolchainName) {
		ToolchainConfiguration.setToolchainName(project, toolchainName);
	}
	
	public static String getToolchainName(IProject project) {
		return ToolchainConfiguration.getToolchainName(project);
	}
	
	public static String getToolchainPath(IProject project) {
		return ToolchainConfiguration.getToolchainPath(project);
	}
	
	public static String getBuildToolsPath() {
		return ToolchainConfiguration.getBuildToolsPath();
	}

	public static void setToolchain(IProject project, String toolchainName, String toolchainPath, String buildToolsPath) {
		ToolchainConfiguration.setToolchain(project, toolchainName, toolchainPath, buildToolsPath);
	}
	
	public static void setToolchainOptions(IProject project, int toolchainIndex) throws BuildException {
		IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project);
		IConfiguration[] configs = buildInfo.getManagedProject().getConfigurations();
		for (IConfiguration config : configs) {
			setOptionsForToolchain(config, toolchainIndex);
		}
	}
	
	public static void setOptionsForToolchain(IConfiguration config, int toolchainIndex) throws BuildException {
		ToolchainConfiguration.setOptionsForToolchain(config, toolchainIndex);
	}
	
	public static int findToolchainByName(String toolchainName) {
		return ToolchainDefinition.findToolchainByName(toolchainName);
	}
	
	public static int getDefaultToolchain() {
		return ToolchainDefinition.getDefault();
	}
	
	public static void updatePreBuildStep(IConfiguration config) {
		ToolchainConfiguration.updatePreBuildStep(config);
	}
	
	public static int getToolchainIndex(String os, String arch, String projectType) {
		int toolchainIndex = 0;
		try {
			toolchainIndex = findToolchainByName(ToolchainUtils.getToolchainName(os, arch, projectType));
		} catch (IndexOutOfBoundsException e) {
			toolchainIndex = getDefaultToolchain();
		}
		return toolchainIndex;
	}
}
